export const REPEAT_INTERVAL = 100;
export const REPEAT_DELAY = 600; //延迟多少秒后可以执行定时器

/**
 * 按住鼠标重复点击
 */
const RepeatClick: any = {
  beforeMount(el: HTMLElement, binding: any) {
    console.log("el", el);
    console.log("binding", binding);
    let interval: ReturnType<typeof setInterval> | null = null;
    let delay: ReturnType<typeof setTimeout> | null = null;

    //拿到绑定需要执行的事件
    const handler = () => binding.value && binding.value();

    const clear = () => {
      if (delay) {
        clearTimeout(delay);
        delay = null;
      }
      if (interval) {
        clearInterval(interval);
        interval = null;
      }
    };

    el.addEventListener("mousedown", (e: MouseEvent) => {
      console.log("e>>>>", e);
      //判断是鼠标左键触发的
      if (e.button !== 0) return;
      handler();

      document.addEventListener("mouseup", clear, { once: true });
      clear();
      delay = setTimeout(() => {
        interval = setInterval(() => {
          handler();
        }, REPEAT_INTERVAL);
      }, REPEAT_DELAY);
    });
  }
};

export default RepeatClick;
